const { host, uploadUrl, tokenKey, initEntryInfo, userInfo } = require("../../config");
const { http } = require("../../util/http");

Page({
  data:{
    auto_focus_placeholder: '请输入昵称',
    nickname: null,
    image: null
  },
  handleInputBlur(e) {
    this.setData({ nickname:e.detail.value })
  },
  onLoad() {
    const info = tt.getStorageSync(userInfo);
    this.setData({
      nickname: info.nickname,
      image: info.image
    })
  },
  chooseImage() {
    tt.chooseImage({
      sourceType: ['album', 'camera'],
      count: 1,
      sizeType: ['compressed'],
      cameraDevice: "front",
      success: res => {
        tt.showToast({
          title: 'success'
        })
        const imagePath = res.tempFilePaths[0];
        const token = tt.getStorageSync(tokenKey)
        const uploadTask = tt.uploadFile({
          url: host + uploadUrl,
          filePath: imagePath,
          name: '123.png',
          header: {
            Authorization: `Bearer ${token}`
          },
          success:res => {
            if (res.statusCode === 200) {
              const data = JSON.parse(res.data);
              this.setData({ image: data.url });
            }
          },
          fail(e) {
            console.log(JSON.stringify(e))
          }
        })
        uploadTask.onProgressUpdate(function(res) {
          console.log("uploading")
          if (res.progress == 100) {
          // upload complete
            console.log(res)
          }
        })
      },
      fail(res) {
        console.log(JSON.stringify(res))
      }
    })
  },
  previewImage: function (e) {
    var current = e.target.dataset.src

    tt.previewImage({
      current: current,
      urls: [current],
      success: res => {
        console.log(JSON.stringify(res))
      },
      fail: res => {
        console.log(JSON.stringify(res))
      }
    })
  },
  removeImg: function() {
    this.setData({ image: null })
  },
  confirm:function() {
    if (!this.data.nickname || !this.data.image) {
      tt.showToast({
        title: '请完善信息！',
        type: 'error'
      })
    } else {
      http(initEntryInfo, 'POST', { nickname: this.data.nickname, image: this.data.image }).then(res => {
        tt.navigateTo({
          url: '/page/index/index',
        });
      })
    }
  }
})